<?php
   class sessionModel extends model
   {
     public function escape($value)
     {
     	return ($this->db->escape($value));
     }
	 
	 public function connexionValide($login, $password){
	 	$res = array("response"=>false);
		$this->db-> escape($login);
		$this->db-> escape($password);
		$password = sha1($password);
		$query = "SELECT * FROM users WHERE `login`='".$login."' AND `password`='".$password."';";
		$data = $this->db->query($query);
		if (isset($data) && $data->count > 0){
			$res['response'] = true;
			$res['values'] = $data;
		}
		return $res;
	 }
	 
	  public function inscriptionValide($login, $password, $password_confirm, $email)
	  {
	  	$res = array("error"=>false);
		
		/**
		 * On protege contre les injections SQL
		 */
		$this->db-> escape($login);
		$this->db-> escape($password);
		$this->db->escape($password_confirm);
		$this->db->escape($email);
		
		$password = sha1($password);
		$password_confirm = sha1($password_confirm);

		/**
		 * On verifie que le login est disponible
		 */
		$query = "SELECT `login` FROM users WHERE `login`='".$login."';";
		$data = $this->db->query($query);
		if (isset($data) && $data->count > 0){
			$res['error'] = true;
			$res['error_login'] = "Identifiant indisponible";
			return $res;
		}
		
		/**
		 *  On verifie que les mots de passe correspondent
		 */
		if ($password != $password_confirm){
			$res['error'] = true;
			$res['error_password'] = "Les mots de passe ne correspondent pas";
			$res['error_password_confirm'] = "Les mots de passe ne correspondent pas";
			return $res;
		}
		
		/**
		 * On verifie la syntaxe de l'email
		 */ 
		$email_regex = '#^[\w.-]+@[\w.-]+\.[a-zA-Z]{2,6}$#';
		if(!preg_match($email_regex,$email)){
			$res['error'] = true;
			$res['error_email'] = "Email invalide";
			return $res;
		}
		
		/**
		 * Pas d'erreur on insere en bdd
		 */
		$query = "INSERT INTO `users`(`login`, `password`,`email`,`droit`) VALUES ('".$login."','".$password."','".$email."','')";
		$this->db->query($query);
		$res['error'] = false;
		return $res;
	}
}
?>